<html lang="zh-CN"><head><meta charset="UTF-8"><style>.nodata  main {width:1000px;margin: auto;}</style></head><body class="nodata " style=""><div class="main_father clearfix d-flex justify-content-center " style="height:100%;"> <div class="container clearfix " id="mainBox"><main><div class="blog-content-box">
<div class="article-header-box">
<div class="article-header">
<div class="article-title-box">
<h1 class="title-article" id="articleContentId">(C卷,100分)- 两数之和绝对值最小（Java & JS & Python）</h1>
</div>
</div>
</div>
<div id="blogHuaweiyunAdvert"></div>

        <div id="article_content" class="article_content clearfix">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/kdoc_html_views-1a98987dfd.css">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/ck_htmledit_views-044f2cf1dc.css">
                <div id="content_views" class="htmledit_views">
                    <h4 id="main-toc">题目描述</h4> 
<p>给定一个从小到大的有序整数序列&#xff08;存在正整数和负整数&#xff09;数组 nums &#xff0c;请你在该数组中找出两个数&#xff0c;其和的绝对值(|nums[x]&#43;nums[y]|)为最小值&#xff0c;并返回这个绝对值。<br /> 每种输入只会对应一个答案。但是&#xff0c;数组中同一个元素不能使用两遍。</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%85%A5%E6%8F%8F%E8%BF%B0">输入描述</h4> 
<p>一个通过空格分割的有序整数序列字符串&#xff0c;最多1000个整数&#xff0c;且整数数值范围是 -65535~65535。</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%87%BA%E6%8F%8F%E8%BF%B0">输出描述</h4> 
<p>两数之和绝对值最小值</p> 
<p></p> 
<h4 id="%E7%94%A8%E4%BE%8B">用例</h4> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:86px;">输入</td><td style="width:412px;">-3 -1 5 7 11 15</td></tr><tr><td style="width:86px;">输出</td><td style="width:412px;">2</td></tr><tr><td style="width:86px;">说明</td><td style="width:412px;">因为 |nums[0] &#43; nums[2]| &#61; |-3 &#43; 5| &#61; 2 最小&#xff0c;所以返回 2。</td></tr></tbody></table> 
<p></p> 
<h4 id="%E9%A2%98%E7%9B%AE%E8%A7%A3%E6%9E%90">题目解析</h4> 
<p>这题和<a href="https://blog.csdn.net/qfc_128220/article/details/127418103?spm&#61;1001.2014.3001.5501" title="算法 - 乱序整数序列两数之和绝对值最小_伏城之外的博客-CSDN博客">算法 - 乱序整数序列两数之和绝对值最小_伏城之外的博客-CSDN博客</a></p> 
<p>几乎一致。只是本题整数序列是升序的。</p> 
<p>本题解析就是上面链接算法题的解析。</p> 
<p></p> 
<h4 id="%E7%AE%97%E6%B3%95%E6%BA%90%E7%A0%81">Java算法源码</h4> 
<p>暴力破解</p> 
<pre><code class="language-java">import java.util.Arrays;
import java.util.Scanner;
 
public class Main {
  public static void main(String[] args) {
    Scanner sc &#61; new Scanner(System.in);
    int[] nums &#61; Arrays.stream(sc.nextLine().split(&#34; &#34;)).mapToInt(Integer::parseInt).toArray();
    System.out.println(getResult(nums));
  }
 
  public static int getResult(int[] nums) {
    int min &#61; Integer.MAX_VALUE;
 
    for (int i &#61; 0; i &lt; nums.length; i&#43;&#43;) {
      for (int j &#61; i &#43; 1; j &lt; nums.length; j&#43;&#43;) {
        int sum &#61; Math.abs(nums[i] &#43; nums[j]);
		min &#61; Math.min(min, sum);
      }
    }
 
    return min;
  }
}</code></pre> 
<p>二分查找优化</p> 
<pre><code class="language-java">import java.util.Arrays;
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner sc &#61; new Scanner(System.in);
    int[] nums &#61; Arrays.stream(sc.nextLine().split(&#34; &#34;)).mapToInt(Integer::parseInt).toArray();
    System.out.println(getResult(nums));
  }

  public static int getResult(int[] nums) {
    //    Arrays.sort(nums);

    int idx &#61; Arrays.binarySearch(nums, 0);
    if (idx &lt; 0) idx &#61; -idx - 1;

    // 全正数&#xff0c;或者 0&#43;多个正数
    if (idx &#61;&#61; 0) return nums[0] &#43; nums[1];

    int n &#61; nums.length;
    // 全负数&#xff0c;或者 多个负数&#43;0
    if (idx &gt;&#61; n - 1) return Math.abs(nums[n - 2] &#43; nums[n - 1]);

    // 下面是有正有负的处理逻辑
    int min &#61; Integer.MAX_VALUE;

    // 负数部分最后两个值
    if (idx &gt;&#61; 2) {
      min &#61; Math.min(min, Math.abs(nums[idx - 2] &#43; nums[idx - 1]));
    }

    // 非负数部分的前两个值
    if (idx &lt; n - 1) {
      min &#61; Math.min(min, Math.abs(nums[idx] &#43; nums[idx &#43; 1]));
    }

    // 非负数部分的数组
    int[] positive &#61; Arrays.copyOfRange(nums, idx, n);
    for (int i &#61; 0; i &lt; idx; i&#43;&#43;) {
      // 注意通过二分查找-nums[i]在positive的有序插入位置j&#xff0c;则最接近-nums[i]的值的位置有两个&#xff1a;j-1和j&#xff0c;其中j位置的元素值 &gt;&#61; -nums[i]&#xff0c;而j -
      // 1位置的元素值 &lt; -nums[i]
      int j &#61; Arrays.binarySearch(positive, -nums[i]);

      if (j &lt; 0) j &#61; -j - 1;
      if (j &#61;&#61; positive.length) j -&#61; 1;

      min &#61; Math.min(min, Math.abs(nums[i] &#43; positive[j]));

      if (j - 1 &gt;&#61; 0) {
        min &#61; Math.min(min, Math.abs(nums[i] &#43; positive[j - 1]));
      }
    }

    return min;
  }
}
</code></pre> 
<h4>JS算法源码</h4> 
<p>暴力破解</p> 
<pre><code class="language-javascript">/* JavaScript Node ACM模式 控制台输入获取 */
const readline &#61; require(&#34;readline&#34;);

const rl &#61; readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

rl.on(&#34;line&#34;, (line) &#61;&gt; {
  const nums &#61; line.split(&#34; &#34;).map(Number);
  console.log(getResult(nums));
});

function getResult(nums) {
  let min &#61; Infinity;

  for (let i &#61; 0; i &lt; nums.length; i&#43;&#43;) {
    for (let j &#61; i &#43; 1; j &lt; nums.length; j&#43;&#43;) {
      const sum &#61; Math.abs(nums[i] &#43; nums[j]);
	  min &#61; Math.min(min, sum);
    }
  }

  return min;
}
</code></pre> 
<p>二分查找优化</p> 
<pre><code class="language-javascript">/* JavaScript Node ACM模式 控制台输入获取 */
const readline &#61; require(&#34;readline&#34;);

const rl &#61; readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

rl.on(&#34;line&#34;, (line) &#61;&gt; {
  const nums &#61; line.split(&#34; &#34;).map(Number);
  console.log(getResult(nums));
});

function getResult(nums) {
  // nums.sort((a, b) &#61;&gt; a - b);

  let idx &#61; binarySearch(nums, 0);
  if (idx &lt; 0) idx &#61; -idx - 1;

  // 全正数&#xff0c;或者 0&#43;多个正数
  if (idx &#61;&#61; 0) return nums[0] &#43; nums[1];

  const n &#61; nums.length;
  // 全负数&#xff0c;或者 多个负数&#43;0
  if (idx &gt;&#61; n - 1)
    return Math.abs(nums[n - 2] &#43; nums[n - 1]);

  // 下面是有正有负的处理逻辑
  let min &#61; Infinity;

  // 负数部分最后两个值
  if (idx &gt;&#61; 2) {
	  min &#61; Math.min(min, Math.abs(nums[idx - 2] &#43; nums[idx - 1]));
  }

  // 非负数部分的前两个值
  if (idx &lt; n - 1) {
	  min &#61; Math.min(min, Math.abs(nums[idx] &#43; nums[idx &#43; 1]));
  }

  // 非负数部分的数组
  const positive &#61; nums.slice(idx);
  for (let i &#61; 0; i &lt; idx; i&#43;&#43;) {
    // 注意通过二分查找-nums[i]在positive的有序插入位置j&#xff0c;则最接近-nums[i]的值的位置有两个&#xff1a;j-1和j&#xff0c;其中j位置的元素值 &gt;&#61; -nums[i]&#xff0c;而j -
    // 1位置的元素值 &lt; -nums[i]
    let j &#61; binarySearch(positive, -nums[i]);

    if (j &lt; 0) j &#61; -j - 1;
    if (j &#61;&#61; positive.length) j -&#61; 1;

	min &#61; Math.min(min, Math.abs(nums[i] &#43; positive[j]));

    if (j - 1 &gt;&#61; 0) {
	  min &#61; Math.min(min, Math.abs(nums[i] &#43; positive[j - 1]));
    }
  }

  return min;
}

function binarySearch(arr, target) {
  let low &#61; 0;
  let high &#61; arr.length - 1;

  while (low &lt;&#61; high) {
    const mid &#61; (low &#43; high) &gt;&gt; 1;
    const midVal &#61; arr[mid];

    if (midVal &gt; target) {
      high &#61; mid - 1;
    } else if (midVal &lt; target) {
      low &#61; mid &#43; 1;
    } else {
      return mid;
    }
  }

  return -low - 1;
}
</code></pre> 
<h4>Python算法源码</h4> 
<p>暴力破解</p> 
<pre><code class="language-python"># 输入获取
import sys

nums &#61; list(map(int, input().split()))


# 算法入口
def getResult():
    minV &#61; sys.maxsize

    for i in range(len(nums)):
        for j in range(i &#43; 1, len(nums)):
            sumV &#61; abs(nums[i] &#43; nums[j])
            minV &#61; min(minV, sumV)

    return minV


# 算法调用
print(getResult())</code></pre> 
<p>二分查找优化</p> 
<pre><code class="language-python">import sys

# 输入获取
nums &#61; list(map(int, input().split()))


def binarySearch(arr, target):
    low &#61; 0
    high &#61; len(arr) - 1

    while low &lt;&#61; high:
        mid &#61; (low &#43; high) &gt;&gt; 1
        midVal &#61; arr[mid]

        if midVal &gt; target:
            high &#61; mid - 1
        elif midVal &lt; target:
            low &#61; mid &#43; 1
        else:
            return mid

    return -low - 1


# 算法入口
def getResult():
    # nums.sort()

    idx &#61; binarySearch(nums, 0)
    if idx &lt; 0:
        idx &#61; -idx - 1

    # 全正数&#xff0c;或者 0&#43;多个正数
    if idx &#61;&#61; 0:
        return nums[0] &#43; nums[1]

    n &#61; len(nums)
    # 全负数&#xff0c;或者 多个负数&#43;0
    if idx &gt;&#61; n - 1:
        return abs(nums[n - 2] &#43; nums[n - 1])

    # 下面是有正有负的处理逻辑
    minV &#61; sys.maxsize

    # 负数部分最后两个值
    if idx &gt;&#61; 2:
        minV &#61; min(minV, abs(nums[idx - 2] &#43; nums[idx - 1]))

    # 非负数部分的前两个值
    if idx &lt; n - 1:
        minV &#61; min(minV, abs(nums[idx] &#43; nums[idx &#43; 1]))

    # 非负数部分的数组
    positive &#61; nums[idx:]
    for i in range(0, idx):
        # 注意通过二分查找-nums[i]在positive的有序插入位置j&#xff0c;则最接近-nums[i]的值的位置有两个&#xff1a;j-1和j&#xff0c;其中j位置的元素值 &gt;&#61; -nums[i]&#xff0c;而j - 1位置的元素值 &lt; -nums[i]
        j &#61; binarySearch(positive, -nums[i])

        if j &lt; 0:
            j &#61; -j - 1

        if j &#61;&#61; len(positive):
            j -&#61; 1

        minV &#61; min(minV, abs(nums[i] &#43; positive[j]))

        if j - 1 &gt;&#61; 0:
            minV &#61; min(minV, abs(nums[i] &#43; positive[j - 1]))

    return minV


# 算法调用
print(getResult())</code></pre>
                </div>
        </div>
        <div id="treeSkill"></div>
        <div id="blogExtensionBox" style="width:400px;margin:auto;margin-top:12px" class="blog-extension-box"></div>
    <script>
  $(function() {
    setTimeout(function () {
      var mathcodeList = document.querySelectorAll('.htmledit_views img.mathcode');
      if (mathcodeList.length > 0) {
        for (let i = 0; i < mathcodeList.length; i++) {
          if (mathcodeList[i].naturalWidth === 0 || mathcodeList[i].naturalHeight === 0) {
            var alt = mathcodeList[i].alt;
            alt = '\\(' + alt + '\\)';
            var curSpan = $('<span class="img-codecogs"></span>');
            curSpan.text(alt);
            $(mathcodeList[i]).before(curSpan);
            $(mathcodeList[i]).remove();
          }
        }
        MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
      }
    }, 1000)
  });
</script>
</div></html>